﻿@inherits _BaseView

<MudPaper>
    <MudToolBar>
        <MudText Color="Color.Primary">
            @Title
        </MudText>
        <MudSpacer />
        <MudIconButton OnClick="OnReloadData" Icon="@Icons.Material.Outlined.Refresh" Color="Color.Secondary" Title="@DashboardResource.StringReload" />
        <MudIconButton OnClick="OpenSearchDialog" Icon="@Icons.Material.Filled.ManageSearch" Color="Color.Tertiary" Title="@DashboardResource.StringSearch" />
    </MudToolBar>
</MudPaper>
<MudCard>
    <MudDivider DividerType="DividerType.FullWidth" />
    <MudCardActions>
        <MudTable ServerData="ServerData" @ref="Table"
                  Dense="@_IsTableDense" Bordered Striped Hover Virtualize FixedFooter Loading="@IsTableLoading"
                   FixedHeader="@_IsTableFixedHeader" Height="@(_IsTableScroll ? "350px" : "100%")"
                   T="GetLogInfo">
             <HeaderContent>
                 <MudTh Class="column-1x"><MudText Align="Align.Center">#</MudText></MudTh>
                 <MudTh><MudTableSortLabel SortLabel="Platform" T="GetLogInfo">Platform</MudTableSortLabel></MudTh>
                 <MudTh><MudTableSortLabel SortLabel="Message" T="GetLogInfo">Message</MudTableSortLabel></MudTh>
                 <MudTh><MudTableSortLabel SortLabel="LogDate" T="GetLogInfo">LogDate</MudTableSortLabel></MudTh>
                 <MudTh><MudTableSortLabel SortLabel="LoggingLevel" T="GetLogInfo">LoggingLevel</MudTableSortLabel></MudTh>
                 <MudTh Class="column-2x">
                     <MudText Align="Align.Left">
                         <MudMenu Icon="@Icons.Material.Filled.MoreVert" Color="Color.Secondary">
                             <MudMenuItem OnClick="@(() => _IsTableDense = _IsTableDense ? false : true)">
                                 <MudSwitch @bind-Value="@_IsTableDense" Color="Color.Secondary">
                                     @DashboardResource.StringDense
                                </MudSwitch>
                            </MudMenuItem>
                            <MudMenuItem OnClick="@(() => _IsTableFixedHeader = _IsTableFixedHeader ? false : true)">
                                <MudSwitch @bind-Value="@_IsTableFixedHeader" Color="Color.Primary">
                                    @DashboardResource.StringFixedHeader
                                </MudSwitch>
                            </MudMenuItem>
                            <MudMenuItem OnClick="@(() => _IsTableScroll = _IsTableScroll ? false : true)">
                                <MudSwitch @bind-Value="@_IsTableScroll" Color="Color.Tertiary">
                                    @DashboardResource.StringScroll
                                </MudSwitch>
                            </MudMenuItem>
                        </MudMenu>
                    </MudText>
                </MudTh>
            </HeaderContent>
            <RowTemplate>
                <MudTd><MudText Class="text-small-2x" Align="Align.Center">@context.RowNum</MudText></MudTd>
                    <MudTd>
                        <MudText Style="@($"color:#F06292;")" Class="text-small-2x">
                            @context?.LoggingPlatformTitle
                    </MudText>
                </MudTd>
                <MudTd>
                    <MudText Color="Color.Success" Class="text-small-2x">
                        @context?.Message
                    </MudText>
                </MudTd>
                <MudTd>
                    <MudText Class="text-small-2x">
                        @context?.LogDate.ToDateString() - @context?.LogDate.ToTimeString()
                    </MudText>
                </MudTd>
                <MudTd>
                    <MudText Style="@($"color:#F06292;")" Class="text-small-2x">
                        @context?.LoggingLevelTitle
                    </MudText>
                </MudTd>
                <MudTd></MudTd>
            </RowTemplate>
            <NoRecordsContent>
                <MudText>@DashboardResource.MessageNoMatchingRecordsFound</MudText>
                </NoRecordsContent>
                <LoadingContent>
                    <MudText>@DashboardResource.StringLoading</MudText>
                </LoadingContent>
                <PagerContent>
                    <MudTablePager PageSizeOptions="new int[]{10, 50, 100, 200, 500, 1000, 2000, 5000}" />
                </PagerContent>
            </MudTable>
        </MudCardActions>
    </MudCard>

    @code {

    [Parameter]
    public string Title { get; set; }

    private IEnumerable<GetLogInfo> Data = new List<GetLogInfo>();
    private MudTable<GetLogInfo> Table = new();
    private TableStateViewModel<FilterLogViewModel> TableState = new();

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }

    private async Task<TableData<GetLogInfo>> ServerData(TableState state, CancellationToken token)
    {
        try
        {
            state.Page++;

            if (state.PageSize == 0)
            {
                state.PageSize = 10;
            }

            TableState.state = new TableState
                {
                    Page = state.Page,
                    PageSize = state.PageSize,
                    SortDirection = state.SortDirection,
                    SortLabel = state.SortLabel,
                };

            if (FilterViewModel != null)
            {
                TableState.Filter = FilterViewModel;
            }

            var PostResult = await Http.PostAsJsonAsync($"{GatewayApi.ToUri}/Logging/PaginationIndex", TableState, token);
            if (PostResult.IsSuccessStatusCode)
            {
                var JsonResult = await PostResult.Content.ReadFromJsonAsync<CallbackResult<PaginatedListViewModel<LogInfo>>>();

                Data = JsonResult.Data.List.AsEnumerable().Select((data, index) => new GetLogInfo
                    {
                        RowNum = ((state.Page - 1) * state.PageSize) + (index + 1),
                        Id = data.Id,
                        Message = data?.Message,
                        LogDate = data.LogDate,
                        LoggingLevelTitle = data?.LoggingLevel?.Title,
                        LoggingPlatformTitle = data?.LoggingPlatform?.Title,
                    }).ToList();

                IsTableLoading = false;
                TableState.Dispose();

                return new TableData<GetLogInfo>()
                    {
                        TotalItems = JsonResult.Data.TotalPages,
                        Items = Data
                    };
            }
            else
            {
                Snackbar.Add(PostResult.Content.ReadAsStringAsync().Result, Severity.Error);
                IsTableLoading = false;
                TableState.Dispose();
                return new TableData<GetLogInfo>()
                    {
                        Items = Data,
                        TotalItems = 0,
                    };
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"{DashboardResource.StringError} : " + ex.Message, Severity.Error);
            IsTableLoading = false;
            TableState.Dispose();
            return new TableData<GetLogInfo>()
                {
                    Items = Data,
                    TotalItems = 0,
                };
        }
    }

    private async Task OnReloadData()
    {
        await Table.ReloadServerData();
    }

    #region - Search -

    private FilterLogViewModel FilterViewModel = new();

    private async Task OpenSearchDialog()
    {
        DialogParameters parameters = new DialogParameters();
        parameters.Add("FilterViewModel", FilterViewModel);

        var dialog = Dialog.Show<DialogFilter>(DashboardResource.StringSearch, parameters,
            new DialogOptions()
                {
                    MaxWidth = MaxWidth.Large,
                    FullWidth = true,
                    Position = DialogPosition.Center,
                });

        var result = await dialog.Result;

        if (!result.Canceled)
        {
            if (result.Data != null)
            {
                FilterViewModel = (FilterLogViewModel)result.Data;
                await OnReloadData();
            }
        }
    }

    #endregion

}
